package cn.itcast.consumer.web;

import cn.itcast.consumer.client.UserClient;
import cn.itcast.consumer.pojo.Order;
import cn.itcast.consumer.pojo.Result;
import cn.itcast.consumer.pojo.User;
import cn.itcast.consumer.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("order")
public class OrderController {


    @Autowired
    private OrderService orderService;

    @Autowired
    private UserClient userClient;

    @GetMapping("{userId}")
    public Order queryOrderByUserId(@PathVariable("userId") Long userId) {
        // 1.根据userId去user-service查询用户信息
        User user = userClient.queryUserById(userId);
        // 2.根据userId查询订单信息，返回订单信息到前端
        return orderService.queryByUserId(user);
    }

    /*@Autowired
    private RestTemplate restTemplate;
    // 开启线程隔离，降级的备用方法的参数列表和返回值必须与隔离方法一样
    @HystrixCommand(fallbackMethod = "queryOrderFallback")
    @GetMapping("{userId}")
    public Result queryOrderByUserId(@PathVariable("userId") Long userId) {
        // 故意让他失败
        if (userId == 1) {
            throw new RuntimeException("我是故意的，触发熔断！");
        }

        // 1.根据userId去user-service查询用户信息
        String url = "http://user-service/user/" + userId;
        User user = restTemplate.getForObject(url, User.class);
        // 2.根据userId查询订单信息，返回订单信息到前端
        Order order = orderService.queryByUserId(user);
        // 3.返回成功结果
        return Result.ok(order);
    }*/

    public Result queryOrderFallback(Long userId) {
        return Result.error("不好意思，服务器太拥挤了，稍后再试！");
    }


    /*@Autowired
    private DiscoveryClient discoveryClient;

//    int index = 0;
    @GetMapping("{userId}")
    public Order queryOrderByUserId(@PathVariable("userId") Long userId) {
        // 手动拉取服务，根据服务id，获取实例列表
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        // 负载均衡，从列表中挑选一个实例
         int index = new Random().nextInt(instances.size());
        // index = (index + 1) % instances.size();
        ServiceInstance instance = instances.get(index);
        // 获取实例的ip和port
        String host = instance.getHost();
        int port = instance.getPort();

        // 1.根据userId去user-service查询用户信息
        String url = String.format("http://%s:%d/user/%d", host, port, userId);
        User user = restTemplate.getForObject(url, User.class);
        // 2.根据userId查询订单信息，返回订单信息到前端
        return orderService.queryByUserId(user);
    }*/
}
